<script setup>
import {differenceInDays} from 'date-fns'
import {nextTick, onMounted, reactive, ref} from "vue";
import {Delete, Download, Plus, ZoomIn, Search} from '@element-plus/icons-vue'
import Table from '@/components/admin/Table.vue'
import Dialog from '@/components/admin/EditDialog.vue'

import {
  GetFosterPetMessageService,
  addFosterService,
  editFosterMessageService,
  deleteFosterNoticeUrlService,
  deleteFosterNoticeUrlsService
} from '@/api/fosterpetmessage.js'
import {ElMessage} from "element-plus";

const multipleTableRef = ref()
const fosterMsg = ref({
  columns: [
    {
      label: '序号',
      prop: 'id',
      width: '50'
    },
    {
      label: '宠物名',
      prop: 'pet_foster_name',
      width: '120'
    },
    {
      label: '寄养人账号名',
      prop: 'pet_foster_master',
      width: '150',
    },
    {
      label: '寄养人姓名',
      prop: 'pet_foster_master_name',
      width: '150',
    },
    {
      label: '手机号',
      prop: 'pet_foster_master_phone',
      width: '250'
    },
    {
      label: '身份证号',
      prop: 'pet_foster_master_IDcard',
      width: '300',
    },
    {
      label: '寄养开始时间',
      prop: 'foster_start_time',
      width: '200'
    },
    {
      label: '寄养结束时间',
      prop: 'foster_end_time',
      width: '150',
    },
    {
      label: '产生价格',
      prop: 'foster_unit_price',
      width: '150',
      type: 'calculate'
    },
    {
      label: '寄养状态',
      prop: 'is_state',
      width: '120',
      type: 'tag',
      formatter: (row) => {
        switch (row.is_state) {
          case 0: {
            return '待寄养'
          }
          case 1: {
            return '寄养中'
          }
          case 2: {
            return '已领回'
          }
        }
      }
    },
    {
      label: '结算状态',
      prop: 'is_checkout',
      width: '120',
      type: 'tag',
      formatter: (row) => {
        switch (row.is_checkout) {
          case 1: {
            return '已结算'
          }
          case 2: {
            return '未结算'
          }
        }
      }
    },
    {
      label: '描述',
      prop: 'description',
      width: '350'
    },
  ],
  data: [],
  loading: true
})
// 获取信息页
const getList = () => {
  GetFosterPetMessageService(all.page, all.limit, all.keyword)
      .then((res) => {
        fosterMsg.value.data = res.data.results.data
        // 获取数据总数
        all.total = res.data.count
        fosterMsg.value.loading = false
        console.log(res.data.results.data)
      })
      .catch((err) => {
        console.log(err)
      })
}
onMounted(() => {
  getList()
})
const all = reactive({
  // 总数
  total: 0,
  // 页
  page: 1,
  // 条
  limit: 10,
  // 关键字
  keyword: ''
})

const sizeChange = (val) => {
  all.limit = val;
  getList()
};
/**
 * 页
 * val -- 当前条
 */
const currentChange = (val) => {
  all.page = val;
  getList()
};

const handleChange = () => {
  fosterMsg.value.loading = true
  setTimeout(() => {
    getList()
  }, 1000)
  console.log('找到了吗', res)
}
// 计算
const calculateFunction = (row) => {
  const startDate = new Date(row.foster_start_time);
  const endDate = new Date(row.foster_end_time);
  // 计算日期差值
  const dateDifference = differenceInDays(endDate, startDate);

  // 计算产生价格
  const fosterUnitPrice = row.foster_unit_price;
  const result = dateDifference * fosterUnitPrice;

  return result;
}
// 行特定高亮
const tableRowClassName = (row, callback) => {
  if (row.is_state == 2 && row.is_checkout == 2) {
    callback('warning-row')
  } else {
    callback('')
  }
}

// 对话框展开
const dialogObject = reactive({
  dialogVisible: false,
  title: '',
  width: '700',
  successBtnText: '确定',
  closeBtnText: '取消',
  isFooter: true
})
const form = ref({
  pet_foster_name: '',
  pet_foster_master: '',
  pet_foster_master_name: '',
  pet_foster_master_phone: '',
  pet_foster_master_IDcard: '',
  foster_start_time: '',
  foster_end_time: '',
  foster_unit_price: null,
  is_state: '',
  is_checkout: '',
  description: ''
})
// 打开对话框组件时需要传入的标题
const addClick = () => {
  dialogObject.dialogVisible = true
  dialogObject.title = '建档'
  formfields.value.base.forEach(item => {
    item.disabled = false
  })

}

// 手机号验证
const validatePhone = (rule, value, callback) => {
  // const reg = /^(\+[0-9]{2,}-?)?1[0-9]{10}$/;
  const reg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
  if (!reg.test(value)) {
    callback(new Error('手机号码格式错误'))
  } else {
    callback()
  }
}

const formfields = ref({
  base: [
    {
      label: '宠物小名', field: 'pet_foster_name',
      rules: [
        {required: true, message: '宠物小名需要填写', trigger: 'blur'}
      ]
    },
    {
      label: '主人账号名', field: 'pet_foster_master', disabled: true,
      rules: [
        {required: true, message: '账号名,需填写', trigger: 'blur'}
      ]
    },
    {
      label: '主人姓名', field: 'pet_foster_master_name', disabled: true,
      rules: [
        {required: true, message: '主人的姓名需要填写，可用代名词', trigger: 'blur'}
      ]
    },
    {
      label: '手机号', field: 'pet_foster_master_phone', disabled: true,
      rules: [
        {required: true, message: '需要留一下手机号', trigger: 'blur'},
        {validator: validatePhone, trigger: 'blur'}
      ]
    },
    {
      label: '身份证号', field: 'pet_foster_master_IDcard', disabled: true,
      rules: [
        {required: true, message: '身份证号需要登记', trigger: 'blur'},
      ]
    },
    {
      label: '寄宠的开始时间', field: 'foster_start_time', type: 'date',
      rules: [
        {required: true, message: '请选择日期', trigger: 'blur'}
      ]
    },
    {
      label: '预计结束时间', field: 'foster_end_time', type: 'alldate',
      rules: [
        {required: true, message: '请选择日期', trigger: 'blur'}
      ]
    },
    {
      label: '日预计单价', field: 'foster_unit_price', disabled: false,
      rules: [
        {required: true, message: '请根据宠物类型填写每日单价', trigger: 'blur'}
      ]
    },
    {
      label: '寄养状态', field: 'is_state', type: 'select',
      options: {
        data: [{label: '待寄养', value: 0}, {label: '寄养中', value: 1}, {label: '已领回', value: 2}]
      },
      rules: [{required: true, message: '选择目前的寄养状态'}]
    },
    {
      label: '结算状态', field: 'is_checkout', type: 'select',
      options: {
        data: [{label: '已结算', value: 1}, {label: '未结算', value: 2}]
      },
      rules: [{required: true, message: '选择目前的结算状态'}]
    },
    {
      label: '其余补充', field: 'description'
    },
  ],
})
// 提交表单增加数据
const handleFormSubmit = async (form) => {
  await addFosterService(form)
      .then((res) => {
        // console.log(res)
        dialogObject.dialogVisible = false
        getList()
      })
      .catch((error) => {
        console.log(error)
      })
}

// 单个数据的编辑
const handleEdit = (index, row) => {
  dialogObject.dialogVisible = true
  dialogObject.title = '调整业务'
  // formfields.value.base.forEach(item=>{
  //   item.disabled=true
  // })
  nextTick(() => {
    form.value.pet_foster_name = row.pet_foster_name
    form.value.pet_foster_master = row.pet_foster_master
    form.value.pet_foster_master_name = row.pet_foster_master_name
    form.value.pet_foster_master_phone = row.pet_foster_master_phone
    form.value.pet_foster_master_IDcard = row.pet_foster_master_IDcard
    form.value.foster_start_time = row.foster_start_time
    form.value.foster_end_time = row.foster_end_time
    form.value.foster_unit_price = row.foster_unit_price
    form.value.is_state = row.is_state
    form.value.is_checkout = row.is_checkout
    form.value.description = row.description
    form.value.id = row.id
  })
  console.log(form)
  console.log('row', row)
}
// 编辑表单提交
const handleFormEdit = async (form) => {
  console.log('form', form)
  await editFosterMessageService(form)
      .then((res) => {
        console.log(res)
        dialogObject.dialogVisible = false
        getList()
      })
      .catch((error) => {
        console.log(error)
      })
}
// 单个删除组件
const handleDelete = (row) => {
  const params = row.id;
  console.log(params)
  deleteFosterNoticeUrlService(params).then((res) => {
    console.log(res.data);
    getList()
  });
}
// 批量选择并删除
const multipleSelection = ref([]);
const selectionchange = (val) => {
  multipleSelection.value = val
  console.log(multipleSelection.value)
}
// 批量选择并删除
const handleDeleteArray = () => {
  if (multipleSelection.value.length <= 0) {
    ElMessage.warning('麻烦你选中了再点')
  }
  for (var i = 0; i < multipleSelection.value.length; i++) {
    const params = multipleSelection.value[i].id;
    const Ids = []
    Ids.push(...multipleSelection.value.map(row => row.id))
    console.log(Ids);
    deleteFosterNoticeUrlsService({Ids: Ids})
        .then((res) => {
          multipleSelection.value = []
          console.log(res.data);
          getList()
        });
  }
}

</script>

<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button type="success" @click="addClick">建立订单</el-button>
        <el-button type="danger" @click="handleDeleteArray">批量删除</el-button>
        <el-input
            v-model="all.keyword"
            class="searchInput"
            placeholder="手机号"
            :prefix-icon="Search"
            @change="handleChange"
        />
        <el-button :icon="Search" @click="handleChange"/>
      </div>
    </template>
    <Table
        ref="multipleTableRef"
        :customdata="fosterMsg"
        :all="all"
        @handleSizeChange="sizeChange"
        @handleCurrentChange="currentChange"
        @handleSelectionChange="selectionchange"
        @rowClassName="tableRowClassName"
    >
      <template #is_state="{row}">
        <el-tag v-if="row.is_state === 0" type="info">待寄养</el-tag>
        <el-tag v-if="row.is_state === 1" type="primary">寄养中</el-tag>
        <el-tag v-if="row.is_state === 2" type="danger">已领回</el-tag>
      </template>
      <template #is_checkout="{row}">
        <el-tag v-if="row.is_checkout === 1" type="primary">已结算</el-tag>
        <el-tag v-if="row.is_checkout === 2" type="danger">未结算</el-tag>
      </template>
      <template #foster_unit_price="{row}">
        {{ calculateFunction(row) }}元
      </template>
      <template #operate>
        <el-table-column fixed="right" label="操作" width="180" show-overflow-tooltip>
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
            <el-popconfirm title="是否确定要删除吗" confirm-button-text="是" cancel-button-text="否"
                           @confirm="handleDelete(scope.row)">
              <template #reference>
                <el-button
                    size="small"
                    type="danger"
                >删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </template>
    </Table>
    <Dialog
        :dialogobject="dialogObject"
        :formlist="formfields.base"
        :model="form"
        @submit="handleFormSubmit"
        @edit="handleFormEdit"
    >
    </Dialog>
  </el-card>
</template>

<style scoped>
.searchInput {
  width: 350px;
  height: 33px;
  margin-left: 20px;
}

</style>